<template>
  <div class="app-container" v-loading="pageLoading">
    <el-form :rules="rules"
             label-position="top"
             ref="saveForm"
             label-width="80px"
             :model="saveForm">

      <el-row :gutter="20">
        <el-col :span="12" :xs="24">
          <el-form-item label="货柜编码（container code）" prop="code">
            <el-input v-model="saveForm.code" placeholder="请输入货柜编码（Please enter container code）"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12" :xs="24">
          <el-form-item label="锁头编码（container lockhead code）" prop="lockCode">
            <el-input v-model="saveForm.lockCode" placeholder="请输入锁头编码（Please enter container lockhead code）"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12" :xs="24">
          <el-form-item label="货柜负责人（container owner）" prop="master">
            <el-input v-model="saveForm.master" placeholder="请输入货柜负责人（Please enter container owner）"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12" :xs="24">
          <el-form-item label="负责人电话（container owner's phone number）" prop="masterPhone">
            <el-input v-model="saveForm.masterPhone"
                      placeholder="请输入货柜负责人电话（Please enter container owner's phone number）"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12" :xs="24">
          <el-form-item label="装柜日期（Loading date）" prop="loadingTime">
            <el-date-picker
              :editable="false"
              v-model="saveForm.loadingTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择装柜日期（Please select Loading date）">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12" :xs="24">
          <el-form-item label="到港日期（Date of arrival）" prop="arrivalTime">
            <el-date-picker
              :editable="false"
              v-model="saveForm.arrivalTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择到港日期（Please select Date of arrival）">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">

        <el-col :span="12" :xs="24">
          <el-form-item label="物流公司（Logistics company）" prop="companyId">
            <el-select v-model="company"
                       placeholder="请选择物流公司（Please select a logistics company）"
                       value-key="id"
                       @change="changeCompany">
              <el-option v-for="item in companyList"
                         :label="item.cname"
                         :value="item"
                         :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>

      <el-row :gutter="20" v-if="saveForm.companyId">
        <el-col :span="12" :xs="24">
          <el-form-item label="公司电话（Logistics company phone）" prop="companyPhone">
            <el-input v-model="saveForm.companyPhone" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" v-if="saveForm.companyId">
        <el-col :span="12" :xs="24">
          <el-form-item label="公司地址（Logistics company address）" prop="companyAddress">
            <el-input v-model="saveForm.companyAddress" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 获取列表 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="客户货物列表（Customer Cargo List）">
            <div class="cargo-list-box">
              <el-empty description="暂无货物" v-if="saveForm.cargoList.length == 0"></el-empty>
              <el-row :gutter="20">
                <el-col :span="8" :xs="24" v-for="(item, index) in saveForm.cargoList" :key="index">
                  <el-card class="box-card">
                    <div class="remove-item" @click="removeItem(item, index)">
                      <i class="el-icon-delete"></i>
                    </div>
                    <el-form-item label="客户姓名（Customer's name）">
                      <el-input v-model="item.customerName"
                                :class="(index == errorIndex && item.customerName.trim() == '') ? 'item-error' : ''"
                                placeholder="请输入客户名称"
                                @blur="getCustomer($event, index)"></el-input>
                    </el-form-item>
                    <el-form-item label="客户代码（Customer's code）">
                      <el-input v-model="item.customerCode" readonly></el-input>
                    </el-form-item>
                    <el-form-item label="客户电话（Customer's phone）">
                      <el-input v-model="item.customerPhone" :readonly="item.userId != ''"></el-input>
                    </el-form-item>
                    <el-form-item label="货物名称（Cargo）">
                      <el-input v-model="item.cargoName"
                                :class="(index == errorIndex && item.cargoName.trim() == '') ? 'item-error' : ''"
                                placeholder="请输入货物名称"></el-input>
                    </el-form-item>
                    <el-form-item label="货物数量（Total）">
                      <el-input v-model="item.cargoNum"
                                placeholder="请输入货物数量"
                                oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')">
                      </el-input>
                    </el-form-item>
                    <el-form-item label="包装数量（packages）">
                      <el-input v-model="item.cargoPackage"
                                placeholder="请输入包装数量"
                                oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')">
                      </el-input>
                    </el-form-item>
                    <el-form-item label="货物体积CBM（Volume）">
                      <el-input v-model="item.cargoSize"
                                @blur="countTotal"
                                oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
                                placeholder="请输入货物体积">
                      </el-input>
                    </el-form-item>
                  </el-card>
                </el-col>

              </el-row>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="hr-item"></div>
      <div class="submit-box">
        <div style="width: 200px;margin-right: 10px">
          <el-input size="small"
                    placeholder="货物总体积"
                    oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
                    v-model="saveForm.cargoVolume">
            <template slot="prepend">总体积：</template>
          </el-input>
        </div>
        <el-button type="success" @click="addCargo">添加货物（{{ saveForm.cargoList.length }}）</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">{{saveForm.id == 0 ? '立即创建' : '更新货柜'}}</el-button>
        <el-button type="info" @click="goTop">回到顶部</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { findCompanyList, getCustomerInfo } from '@/api/system/common'
import { addCounter, getCounterEditInfo, updateCounter } from '@/api/system/counter'
import { delGoods } from '@/api/system/counter-goods'

export default {
  name: "save-order",
  data() {
    return {
      pageLoading: false,
      pageScrollTop: 0,
      companyList: [],
      company: {},
      errorIndex: null,
      saveForm: {
        id: 0,
        code: '',
        lockCode: '',
        master: '',
        masterPhone: '',
        companyId: '',
        companyPhone: '',
        companyAddress: '',
        loadingTime: new Date(),
        arrivalTime: new Date(),
        cargoVolume: 0.0,
        cargoList: []
      },
      rules: {
        code: [
          {required: true, message: '货柜编码不能为空（container code cannot be empty）', trigger: 'blur'}
        ],
        lockCode: [
          {required: true, message: '锁头编码不能为空（container lockhead code be empty）', trigger: 'blur'}
        ],
        master: [
          {required: true, message: '货柜负责人不能为空（container owner cannot be empty）', trigger: 'blur'}
        ],
        masterPhone: [
          {
            required: true,
            message: '负责人电话不能为空（container owner\'s phone number cannot be empty）',
            trigger: 'blur'
          }
        ],
        loadingTime: [
          {required: true, message: '请选择装柜日期（Please select a Loading date）', trigger: 'change'}
        ],
        arrivalTime: [
          {required: true, message: '请选择到港日期（Please select a Date of arrival）', trigger: 'change'}
        ],
        companyId: [
          {required: true, message: '请选择物流公司（Please select a Logistics company）', trigger: 'change'}
        ],
      }
    }
  },
  async created() {
    this.companyList = (await findCompanyList()).data;
    if (this.$route.params.id != 0) {
      await this.editInfo(this.$route.params.id);
    }
  },
  methods: {
    async editInfo(id) {
      try {
        this.pageLoading = true;
        const { data } = await getCounterEditInfo(id);
        this.saveForm = data;
        this.company = data.company;
        this.saveForm.companyPhone = data.company.phone;
        this.saveForm.companyAddress = data.company.cname;
        this.pageLoading = false;
      }catch (e) {
        this.pageLoading = false;
      }
    },
    addCargo() {
      const temp = {
        id: 0,
        customerName: '',
        customerPhone: '',
        cargoName: '',
        cargoPackage: 0,
        cargoNum: 0,
        cargoSize: 0
      }
      this.saveForm.cargoList.push(temp);
      if (document.documentElement.scrollHeight != document.documentElement.scrollTop) {
        setTimeout(() => {
          document.documentElement.scrollTo({
            top: document.documentElement.scrollHeight,
            behavior: "smooth"
          });
        },200);
      }
    },
    submitForm() {
      this.$refs["saveForm"].validate((valid) => {
        if (valid) {
          this.saveForm.loadingTime = this.parseTime(this.saveForm.loadingTime)
          this.saveForm.arrivalTime = this.parseTime(this.saveForm.arrivalTime)
          if (this.saveForm.cargoList.length > 0) {
            for (let i = 0; i < this.saveForm.cargoList.length; i++) {
              if (this.saveForm.cargoList[i].cargoName.trim() == '' || this.saveForm.cargoList[i].customerName.trim() == '') {
                this.errorIndex = i;
                this.$message.error("货物列表有必填表单请完善！")
                return false;
              }
            }
          }
          if (this.saveForm.id == 0) {
            this.pageLoading = true;
            addCounter(this.saveForm).then((res) => {
              this.pageLoading = false;
              this.$message.success(res.msg)
              this.resetForm();
              this.saveForm.cargoVolume = 0.0;
            }).catch((e) => {
              this.pageLoading = false;
            })
          }
          else {
            this.pageLoading = true;
            updateCounter(this.saveForm).then((res) => {
              this.pageLoading = false;
              this.$message.success(res.msg)
            }).catch((e) => {
              this.pageLoading = false;
            })
          }
        } else {
          setTimeout(() => {
            document.documentElement.scrollTo({
              top: 0,
              behavior: "smooth"
            });
          },200);
        }
      });
    },
    async resetForm() {
      if (this.saveForm.id != 0) {
        await this.editInfo(this.saveForm.id)
      } else {
        this.saveForm.cargoList = [];
        this.company = {};
        this.saveForm.companyId = '';
        this.saveForm.companyPhone = '';
        this.saveForm.companyAddress = '';
        this.$refs["saveForm"].resetFields();
      }
    },
    // 物流公司切换
    changeCompany(val) {
      this.saveForm.companyId = val.id;
      this.saveForm.companyAddress = val.address;
      this.saveForm.companyPhone = val.phone;
    },
    // 删除货物
    async removeItem(val,index) {
      this.saveForm.cargoList.splice(index, 1);
      this.saveForm.cargoVolume -= val.cargoSize;
      if (this.saveForm.cargoVolume < 0) {
        this.saveForm.cargoVolume = 0.0;
      }
      this.saveForm.cargoVolume = this.saveForm.cargoVolume.toFixed(2);
      if (val.id != 0) {
        try {
          this.pageLoading = true;
          await delGoods(val.id);
          this.submitForm();
          this.pageLoading = false;
        } catch (e) {
          this.pageLoading = false;
        }
      }
    },
    // 获取客户详情
    async getCustomer(val, index) {
      const value = this.saveForm.cargoList[index].customerName.trim();
      if (value != '') {
        try {
          this.pageLoading = true;
          const data = (await getCustomerInfo(value)).data;
          this.saveForm.cargoList[index].userId = data.userId == null ? '' : data.userId;
          this.saveForm.cargoList[index].customerPhone = data.phone == null ? '' : data.phone;
          this.saveForm.cargoList[index].customerCode = data.code == null ? '' : data.code;
          this.pageLoading = false;
        }catch (e) {
          this.pageLoading = false;
        }
      }
    },
    // 页面回到顶部
    async goTop() {
      setTimeout(() => {
        document.documentElement.scrollTo({
          top: 0,
          behavior: "smooth"
        });
      },200);
    },
    // 计算总体积
    countTotal() {
      this.saveForm.cargoVolume = 0.0;
      for (let i = 0; i < this.saveForm.cargoList.length; i++) {
        this.saveForm.cargoVolume += Number(this.saveForm.cargoList[i].cargoSize);
      }
      this.saveForm.cargoVolume = this.saveForm.cargoVolume.toFixed(2);
    }
  }
}
</script>

<style lang="scss" scoped>

.app-container {
  .el-date-editor {
    width: 100% !important;
  }
  .el-select {
    width: 100%;
  }
  .cargo-list-box {
    width: 100%;
    box-sizing: border-box;
    .item-error {
      border: 1px red solid;
    }
    .box-card {
      position: relative;
      margin-bottom: 10px;
      ::v-deep .el-form-item__label {
        padding: 0 !important;
      }
      ::v-deep .el-card__body {
        padding: 10px 20px 10px 20px !important;
        p {
          margin: 0 !important;
          font-size: 25px;
          font-weight: 600;
        }
      }
      .remove-item {
        position: absolute;
        top: 0;
        right: 0;
        width: 50px;
        height: 50px;
        cursor: pointer;
        background: #1e90ff;
        border-radius: 0px 0px 0px 50px;
        .el-icon-delete {
          font-size: 20px;
          color: #ffffff;
          padding: 10px 0 0 20px;
        }
      }
    }
  }
  .hr-item {
    margin-bottom: 15px;
  }
  .submit-box {
    width: 100%;
    height: 55px;
    position: fixed;
    margin: 0 !important;
    left: 0;
    bottom: 0;
    z-index: 9;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding-right: 20px;
    background: #ffffff;
    -moz-box-shadow:0px -2px 2px #D1D1D1; -webkit-box-shadow:0px -2px 2px #D1D1D1; box-shadow:0px -2px 2px #D1D1D1;
  }
  @media screen and (max-width: 750px) {
    .submit-box {
      height: 80px;
      padding-right: 0px;
      flex-wrap: wrap;
      justify-content: center;
      .el-button {
        padding: 8px 10px !important;
      }
    }
    .hr-item {
      margin-bottom: 35px;
    }
  }
}
</style>
